﻿using System;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using StaffWars.Services;

namespace StaffWarsFm.Controls
{
    public class UserImage : Image
    {
        public static DependencyProperty UserNameProperty = DependencyProperty.Register(
            "UserName",
            typeof (string),
            typeof (UserImage),
            new PropertyMetadata(UserNameProperty_Changed));

        private static void UserNameProperty_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var userImage = (UserImage) d;
            var userName = (string)e.NewValue;

            userImage.LoadUserImage(userName);
        }

        public string UserName
        {
            get { return (string) GetValue(UserNameProperty); }
            set { SetValue(UserNameProperty, value); }
        }

        private void LoadUserImage(string userName)
        {
            ThreadPool.QueueUserWorkItem(delegate
            {
                try
                {
                    var userProfileUrl = string.Format("http://last.fm/user/{0}", userName);
                    var screenScraper = new ScreenScrapingService();
                    var photoElement = screenScraper.GetElementByXPath(userProfileUrl, "//img[@class='photo']");
                    var src = photoElement.Attributes["src"].Value;

                    Dispatcher.Invoke(() => Source = new BitmapImage(new Uri(src)));
                }
                catch (Exception)
                {
                }
            });
        }
    }
}
